package mvc.struts.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mvc.struts.form.ActionForm;
import mvc.struts.form.FullForm;
import mvc.struts.form.XmlBean;



public class ActionServlet extends HttpServlet{
	
	private static final long serialVersionUID = 5923913779505909456L;

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String path=getPanduan(req.getServletPath());
		Map<String,XmlBean>map=(Map<String, XmlBean>) this.getServletContext().getAttribute("struts");
		XmlBean xml=map.get(path);
		String formClass=xml.getFormClass();
		ActionForm form=FullForm.full(formClass,req);
		String actionType=xml.getActionClass();
		Action action=null;
		String url="";
		try {
			Class<?> clazz=Class.forName(actionType);
			action=(Action) clazz.newInstance();
			url=action.execute(req, resp, form, xml.getActionForward());
		} catch (Exception e) {
			e.printStackTrace();
		}
		RequestDispatcher dispatcher=req.getRequestDispatcher(url);
		dispatcher.forward(req, resp);
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}
	
	private static String getPanduan(String path){
		return path.split("\\.")[0];
	}

}
